"""
统一配置模式定义
"""
from typing import Dict, List, Optional, Any, Union
from pydantic import BaseModel, Field, validator
from enum import Enum

class ServiceStatus(str, Enum):
    """服务状态枚举"""
    ENABLED = "enabled"
    DISABLED = "disabled"
    MAINTENANCE = "maintenance"

class ServiceConfig(BaseModel):
    """单个服务配置模式"""
    name: str = Field(..., description="服务名称")
    port: int = Field(..., ge=1024, le=65535, description="服务端口")
    host: str = Field(default="0.0.0.0", description="绑定主机")
    enabled: bool = Field(default=True, description="是否启用")
    health_check: str = Field(default="/health", description="健康检查路径")
    docs_url: str = Field(default="/docs", description="API文档路径")
    timeout: int = Field(default=30, description="请求超时时间(秒)")
    
    @validator('port')
    def validate_port(cls, v):
        """验证端口范围"""
        if not (1024 <= v <= 65535):
            raise ValueError('端口必须在1024-65535范围内')
        return v

class DatabaseConfig(BaseModel):
    """数据库配置模式"""
    type: str = Field(..., description="数据库类型")
    host: str = Field(..., description="数据库主机")
    port: int = Field(..., description="数据库端口")
    database: Optional[str] = Field(default=None, description="数据库名")
    username: Optional[str] = Field(default=None, description="用户名")
    password: Optional[str] = Field(default=None, description="密码")
    pool_size: int = Field(default=10, description="连接池大小")
    max_overflow: int = Field(default=20, description="最大溢出连接数")
    echo: bool = Field(default=False, description="是否显示SQL")
    
    # InfluxDB特有字段
    org: Optional[str] = Field(default=None, description="InfluxDB组织")
    bucket: Optional[str] = Field(default=None, description="InfluxDB存储桶")
    token: Optional[str] = Field(default=None, description="InfluxDB令牌")

class SecurityConfig(BaseModel):
    """安全配置模式"""
    jwt_secret_key: str = Field(..., description="JWT密钥")
    jwt_algorithm: str = Field(default="HS256", description="JWT算法")
    jwt_access_token_expire_minutes: int = Field(default=30, description="访问令牌过期时间")
    jwt_refresh_token_expire_days: int = Field(default=7, description="刷新令牌过期天数")
    cors_origins: List[str] = Field(default=["*"], description="CORS允许的源")
    cors_methods: List[str] = Field(default=["*"], description="CORS允许的方法")

class UnifiedConfig(BaseModel):
    """统一配置根模式"""
    version: str = Field(..., description="配置版本")
    config_schema: str = Field(..., description="配置模式标识")
    
    # 全局配置
    global_config: Dict[str, Any] = Field(alias="global")
    
    # 服务配置
    services: Dict[str, ServiceConfig] = Field(..., description="服务配置映射")
    
    # 数据库配置
    databases: Dict[str, DatabaseConfig] = Field(..., description="数据库配置映射")
    
    # 安全配置
    security: SecurityConfig = Field(..., description="安全配置")
    
    # 其他配置
    cache: Dict[str, Any] = Field(default={}, description="缓存配置")
    logging: Dict[str, Any] = Field(default={}, description="日志配置")
    monitoring: Dict[str, Any] = Field(default={}, description="监控配置")
    external_services: Dict[str, Any] = Field(default={}, description="外部服务配置")
    
    class Config:
        populate_by_name = True
    
    @validator('services')
    def validate_unique_ports(cls, v):
        """验证服务端口唯一性"""
        ports = [service.port for service in v.values() if service.enabled]
        if len(ports) != len(set(ports)):
            duplicates = [port for port in set(ports) if ports.count(port) > 1]
            raise ValueError(f'发现重复端口: {duplicates}')
        return v
    
    def get_service_url(self, service_name: str) -> Optional[str]:
        """获取服务完整URL"""
        service = self.services.get(service_name)
        if service and service.enabled:
            return f"http://{service.host}:{service.port}"
        return None
    
    def get_enabled_services(self) -> Dict[str, ServiceConfig]:
        """获取所有启用的服务"""
        return {name: service for name, service in self.services.items() if service.enabled}
